<template>
  <div class="fireworks">
    <div class="fireworks-item"
      v-for="fireworks in fireworksList"
      :key="fireworks.id"
      :style="fireworks | fireworks">
      <div class="power" :style="fireworks | color"></div>
      <div
        v-for="(spark, j) in fireworks.sparkList"
        :key="j"
        class="spark"
        :class="'spark' + (j + 1)"
        :style="spark | spark">
        <div class="spark-child" :style="fireworks | color"></div>
      </div>
    </div>
  </div>
</template>

<script>
  import { getRandom } from '@/util'

  export default {
    props: {
      count: {
        type: Number,
        default: 12
      }
    },
    data() {
      return {
        // color: [
        //   '#2ec7c9', '#b6a2de', '#5ab1ef', '#ffb980', '#d87a80',
        //   '#8d98b3', '#e5cf0d', '#97b552', '#95706d', '#dc69aa',
        //   '#07a2a4', '#9a7fd1', '#588dd5', '#f5994e', '#c05050',
        //   '#59678c', '#c9ab00', '#7eb00a', '#6f5553', '#c14089'
        // ],
        fireworksList: []
      }
    },
    mounted() {
      this.init()
    },
    filters: {
      fireworks(item) {
        return {
          left: item.left + 'px'
        }
      },
      spark(item) {
        return {
          transform: `rotate(${item.rotate}deg)`
        }
      },
      color(item) {
        return {
          'background-color': item.color || '#fff'
        }
      }
    },
    methods: {
      init() {
        this.initFireworksList()
      },
      initFireworksList() {
        setTimeout(() => {
          if (this.fireworksList.length < 5) {
            let windowWidth = window.innerWidth - 100;
            let item = {
              id: this.getId(),
              left: getRandom(0, windowWidth),
              color: '#fff628',
              sparkList: this.initSparkList(),
              done: false
            }
            setTimeout(() => {
              item.done = true
              this.fireworksList = this.fireworksList.filter(item => !item.done)
            }, 4000)
            this.fireworksList.push(item)
          }
          this.initFireworksList()
        }, getRandom(200, 1000))
      },
      initSparkList(color) {
        let count = this.count || 1
        let list = []
        for (let i = 0; i < count; i++) {
          let item = {
            rotate: 360 / count * i,
            color: color || '#fff628'
          }
          list.push(item)
        }
        return list
      },
      getId() {
        if (!this.id) {
          this.id = 1
        } else {
          this.id += 1
        }
        return this.id 
      }
    }
  }
</script>
